let data = {};
let myChart = null;
document.addEventListener('DOMContentLoaded', function() {

    //模态框
    const modal = document.getElementById("modal");
    const closeBtn = document.getElementById("close");

    // 显示模态框
    modal.classList.add('show');

    // 关闭模态框
    closeBtn.onclick = function() {
        modal.classList.remove('show');
    };

    // 点击模态框外部关闭模态框
    window.onclick = function(event) {
        if (event.target === modal) {
            modal.classList.remove('show');
        }
    };

    // 表单提交
    document.getElementById("infoForm").onsubmit = function(event) {
        event.preventDefault(); // 防止表单默认提交行为

        // 获取表单数据
        const name = document.getElementById("name").value;
        const email = document.getElementById("email").value;

        // 处理表单数据 (例如: 发送到服务器或进行验证)
        console.log(`姓名: ${name}, 电子邮件: ${email}`);

        // 隐藏模态框
        modal.classList.remove('show');
    };


    const chatInput = document.getElementById('chatInput');
    const sendRequestButton = document.getElementById('sendRequestButton');
    const chatMessages = document.getElementById('chatMessages');

    sendRequestButton.addEventListener('click', function () {
        const requestText = chatInput.value.trim();
        if (requestText === '') return;

        appendMessage('', requestText, null,'sent');
        chatInput.value = '';

        // 显示加载动画
        $('#loading').show();

        // 销毁现有图表
        if (myChart) {
            myChart.destroy();
        }

        // 隐藏图表按钮
        $('#chartButtons').hide();

        // 销毁现有 DataTable 实例（如果有）
        if ($.fn.DataTable.isDataTable('#dynamicTable')) {
            $('#dynamicTable').DataTable().destroy();
            $('#tableHead').empty();
            $('#tableBody').empty();
        }

        const requestData = {
            ip: "192.168.0.120",
            port: "3306",
            dbName: "bigdata",
            account: "root",
            password: "root",
            sql: "1",
            message: requestText
        };

        $.ajax({
            type: 'POST',
            url: 'http://localhost:8989/dbChat',
            contentType: 'application/json',
            data: JSON.stringify(requestData),
            success: function (response) {
                console.log(response);
                const responseText = response.message;
                appendMessage(response.recording.id, responseText, null,'received');

                if (response.display_type === 'histogram') {
                    data = JSON.parse(response.data);
                    $('#chartButtons').show();
                    showHistogram(data);
                } else if (response.display_type === 'table') {
                    $('#chartButtons').hide();
                    showTable(JSON.parse(response.data));
                }

                chatMessages.scrollTop = chatMessages.scrollHeight;

                // 隐藏加载动画
                $('#loading').hide();
            },
            error: function (xhr, status, error) {
                console.error('Error:', error);
                appendMessage( '','An error occurred while processing your request.', null,'received');

                // 隐藏加载动画
                $('#loading').hide();
            }
        });
    });


    function showHistogram(data) {
        myChart = new Chart(document.getElementById('myChart'), {
            type: 'bar',
            data: data,
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    function showTable(data) {
        $('#tableHead').empty();
        $('#tableBody').empty();

        const firstResult = data.results[0];

        let tableHead = '<tr>';
        Object.keys(firstResult).forEach(function(key) {
            tableHead += '<th>' + key + '</th>';
        });
        tableHead += '</tr>';
        $('#tableHead').append(tableHead);

        data.results.forEach(function(item) {
            let row = '<tr>';
            Object.values(item).forEach(function(value) {
                row += '<td>' + value + '</td>';
            });
            row += '</tr>';
            $('#tableBody').append(row);
        });

        $('#dynamicTable').DataTable({
            "destroy": true,
            "pageLength": 10,
            "paging": true
        });
    }

    function appendMessage(id, sender, message, type) {
        const chatMessages = document.querySelector('.chat-messages');

        const messageElement = document.createElement('div');
        messageElement.classList.add('message', type);
        messageElement.setAttribute('data-id', id); // 添加 ID

        // 点击事件处理程序
        messageElement.addEventListener('click', async () => {
            const response = await fetch(`/getHistory/${id}`);
            const historyData = await response.json();
            displayHistory(historyData);
        });

        const senderElement = document.createElement('div');
        senderElement.classList.add('sender');
        senderElement.textContent = sender;

        const textElement = document.createElement('div');
        textElement.classList.add('text');
        textElement.textContent = message;

        const timestampElement = document.createElement('div');
        timestampElement.classList.add('message-time');
        timestampElement.textContent = new Date().toLocaleTimeString();

        messageElement.appendChild(senderElement);
        messageElement.appendChild(textElement);
        messageElement.appendChild(timestampElement);

        chatMessages.appendChild(messageElement);
    }

// 显示历史记录的函数
    function displayHistory(response) {

        if (response['display_type'] === 'histogram') {
            // 销毁现有图表
            if (myChart) {
                myChart.destroy();
            }

            // 隐藏图表按钮
            $('#chartButtons').hide();

            // 销毁现有 DataTable 实例（如果有）
            if ($.fn.DataTable.isDataTable('#dynamicTable')) {
                $('#dynamicTable').DataTable().destroy();
                $('#tableHead').empty();
                $('#tableBody').empty();
            }
            data = JSON.parse(response['data']);
            $('#chartButtons').show();
            showHistogram(data);
        } else if (response['display_type'] === 'table') {
            // 销毁现有图表
            if (myChart) {
                myChart.destroy();
            }

            // 隐藏图表按钮
            $('#chartButtons').hide();

            // 销毁现有 DataTable 实例（如果有）
            if ($.fn.DataTable.isDataTable('#dynamicTable')) {
                $('#dynamicTable').DataTable().destroy();
                $('#tableHead').empty();
                $('#tableBody').empty();
            }
            $('#chartButtons').hide();
            showTable(JSON.parse(response['data']));
        }else{
            alert("改回答没有可视化显示！")
            console.log("暂无可显示数据")
        }

        // 隐藏加载动画
        $('#loading').hide();
    }



});

function changeChartType(type) {
    if (myChart) {
        myChart.destroy();
    }
    myChart = new Chart(document.getElementById('myChart'), {
        type: type,
        data: data,
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: '数据展示'
                }
            },
            cutout: type === 'doughnut' ? '50%' : undefined
        }
    });
}